package com.sxt.sys.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sxt.sys.SYSConstast.SYSConstast;
import com.sxt.sys.domain.Permission;
import com.sxt.sys.domain.User;
import com.sxt.sys.service.PermissionService;
import com.sxt.sys.service.UserService;
import com.sxt.sys.utils.ActiverUser;
@Component
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private PermissionService permissionService;
	
	public String getName() {
		
		return this.getClass().getSimpleName();
	}
	
	/**
	 * 授权
	 * 
	 */
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ActiverUser activerUser = (ActiverUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
		if(activerUser.getUser().getType()==SYSConstast.USER_TYPE_SUPER) {
			info.addStringPermission("*:*");
		}else {
			if(null!=activerUser.getRoles()&&!activerUser.getRoles().isEmpty()) {
				info.addRoles(activerUser.getRoles());
			}
			if(null!=activerUser.getPermissions()&&!activerUser.getPermissions().isEmpty()) {
				info.addStringPermissions(activerUser.getPermissions());
			}
			
		}
		
		
		return info;
	}

	/**
	 * 认证
	 * 
	 * (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String loginname = token.getPrincipal().toString();
		User user = userService.queryByUserLoginName(loginname);
		if(null!=user) {
			ActiverUser activerUser = new ActiverUser();
			activerUser.setUser(user);
			if(user.getType()==SYSConstast.USER_TYPE_NORMAL) {
				List<String> userId = permissionService.queryPermissionByUserIdForStrList(user.getId());
				activerUser.setPermissions(userId);
			}
			ByteSource bytesource = ByteSource.Util.bytes(user.getSalt());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPwd(), bytesource, getName());
			return info;
		}else {
		return null;
		
		}
	}

}
